﻿using System.IO;
using System.Xml.Serialization;
using System.Text;
using System.Security.Cryptography;

namespace Kangaroo.Configuration.ConfigSaver
{
    public class XmlConfigSaver : IConfigSaver
    {
        public TConfig Load<TConfig>(string filename)
        {
            var serializer = new XmlSerializer(typeof(TConfig));
            using(var stream = File.OpenRead(filename))
            {
                var config = (TConfig)serializer.Deserialize(stream);
                return config;
            }
        }

        public void Save<TConfig>(TConfig config, string filename)
        {
            var serializer = new XmlSerializer(typeof(TConfig));
            using(var stream = File.Open(filename, FileMode.Create, FileAccess.Write))
            {
                serializer.Serialize(stream, config);
            }
        }


        public TConfig LoadWithDecrypt<TConfig>(string filename)
        {
            try
            {
                string password = @"myKey123"; // Your Key Here

                UnicodeEncoding UE = new UnicodeEncoding();
                byte[] key = UE.GetBytes(password);

                FileStream fsCrypt = new FileStream(filename, FileMode.Open);

                RijndaelManaged RMCrypto = new RijndaelManaged();

                CryptoStream cs = new CryptoStream(fsCrypt,
                    RMCrypto.CreateDecryptor(key, key),
                    CryptoStreamMode.Read);

                MemoryStream msOut = new MemoryStream();

                int data;

                while ((data = cs.ReadByte()) != -1)
                    msOut.WriteByte((byte)data);
                var serializer = new XmlSerializer(typeof(TConfig));
                msOut.Seek(0, SeekOrigin.Begin);
                var config = (TConfig)serializer.Deserialize(msOut);
                msOut.Close();
                cs.Close();
                fsCrypt.Close();

                return config;
                
            }
            catch
            {
                throw;
            }
        }

        private static void DecryptFile(string inputFile)
        {
            
        }
    }


}
